<template>
  <a-upload
    :before-upload="beforeUpload"
    :customRequest="customRequest"
    :file-list="fileList"
    :show-upload-list="false"
  >
    <a-button>
      <a-icon type="upload" />
      选择视频文件
    </a-button>
  </a-upload>
  <div v-if="previewUrl" style="margin-top: 16px">
    <video
      :src="localPreviewUrl"
      controls
      style="width: 100%; max-width: 600px"
    ></video>
  </div>
</template>

<script>
  import { Upload, Button, message } from 'ant-design-vue'
  import VabIcon from '@/layout/vab-icon'
  import { videoUpload } from '@/api/common'

  export default {
    components: {
      AUpload: Upload,
      AButton: Button,
      AIcon: VabIcon,
    },
    props: {
      previewUrl: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        fileList: [],
        localPreviewUrl: this.previewUrl,
      }
    },
    methods: {
      beforeUpload(file) {
        // 添加自定义校验逻辑，确保只上传视频文件
        const isVideo = file.type.startsWith('video/')
        if (!isVideo) {
          message.error('只能上传视频文件！')
        }
        return isVideo
      },
      customRequest({ file }) {
        // 自定义上传逻辑
        const formData = new FormData()
        formData.append('video', file)
        formData.append('label', 'article')

        videoUpload(formData).then((data) => {
          message.success('上传成功')
          this.localPreviewUrl = data.data
          // 触发自定义事件，将视频路径传递给父组件
          this.$emit('video-uploaded', data.data)
        })
      },
    },
  }
</script>

<style scoped>
  /* 自定义样式可在此添加 */
</style>
